package com.atguigu.daijia.order.service.impl;

import com.alibaba.nacos.common.utils.UuidUtils;
import com.atguigu.daijia.model.entity.order.OrderInfo;
import com.atguigu.daijia.model.entity.order.OrderStatusLog;
import com.atguigu.daijia.model.enums.OrderStatus;
import com.atguigu.daijia.model.form.order.OrderInfoForm;
import com.atguigu.daijia.order.mapper.OrderInfoMapper;
import com.atguigu.daijia.order.mapper.OrderStatusLogMapper;
import com.atguigu.daijia.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    private final OrderStatusLogMapper orderStatusLogMapper;

    /**
     * 保存订单信息
     *
     * @param orderInfoForm
     * @return
     */
    @Override
    public Long saveOrderInfo(OrderInfoForm orderInfoForm) {
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoForm,orderInfo);
        String orderNum = UUID.randomUUID().toString().replace("-", "");
        orderInfo.setOrderNo(orderNum);
        orderInfo.setStatus(OrderStatus.WAITING_ACCEPT.getStatus());
        save(orderInfo);

        logOrderStatus(orderInfo);
        return 0L;
    }

    /**
     * 根据订单id查询订单状态
     *
     * @param orderId
     * @return
     */
    @Override
    public Integer getOrderStatus(Long orderId) {
        OrderInfo orderInfo = lambdaQuery().select(OrderInfo::getStatus)
                .eq(OrderInfo::getId, orderId)
                .one();
        if(Objects.isNull(orderInfo)){
            return OrderStatus.NULL_ORDER.getStatus();
        }
        return orderInfo.getStatus();
    }

    private  void logOrderStatus(OrderInfo orderInfo) {
        OrderStatusLog orderStatusLog = new OrderStatusLog();
        orderStatusLog.setOrderId(orderInfo.getId());
        orderStatusLog.setOrderStatus(OrderStatus.WAITING_ACCEPT.getStatus());
        orderStatusLog.setOperateTime(new Date());
        orderStatusLog.setCreateTime(new Date());
        orderStatusLog.setUpdateTime(new Date());
        orderStatusLogMapper.insert(orderStatusLog);
    }
}
